package org.mat.ipaas.ucenter.service.modules.system.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.mat.framework.lang.dto.MatApiResponse;
import org.mat.ipaas.ucenter.biz.common.config.TenantContext;
import org.mat.ipaas.ucenter.biz.common.constant.CommonConstant;
import org.mat.ipaas.ucenter.biz.common.system.query.QueryGenerator;
import org.mat.ipaas.ucenter.biz.common.util.oConvertUtils;
import org.mat.ipaas.ucenter.biz.config.mybatis.MybatisPlusSaasConfig;
import org.mat.ipaas.ucenter.biz.modules.system.entity.SysPermission;
import org.mat.ipaas.ucenter.biz.modules.system.entity.SysPermissionDataRule;
import org.mat.ipaas.ucenter.biz.modules.system.entity.SysRole;
import org.mat.ipaas.ucenter.biz.modules.system.entity.SysRolePermission;
import org.mat.ipaas.ucenter.biz.modules.system.model.TreeModel;
import org.mat.ipaas.ucenter.biz.modules.system.service.*;
import org.mat.ipaas.ucenter.service.api.system.SysRoleRestAPI;
import org.mat.ipaas.ucenter.service.dto.system.entity.SysRoleDTO;
import org.mat.ipaas.ucenter.service.modules.SessionService;
import org.mat.ipaas.ucenter.service.util.SessionUtils;
import org.mat.ipaas.ucenter.service.dto.system.vo.LoginUserDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.openfeign.SpringQueryMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * <p>
 * 角色表 前端控制器
 * </p>
 *
 * @Author scott
 * @since 2018-12-19
 */
@RestController
@RequestMapping("/sys/role")
@Slf4j
public class SysRoleController implements SysRoleRestAPI {

    @Autowired
    private SessionService sessionService;
    @Autowired
    private ISysRoleService sysRoleService;

    @Autowired
    private ISysPermissionDataRuleService sysPermissionDataRuleService;

    @Autowired
    private ISysRolePermissionService sysRolePermissionService;

    @Autowired
    private ISysPermissionService sysPermissionService;

    @Autowired
    private ISysUserRoleService sysUserRoleService;

    /**
     * 分页列表查询 【系统角色，不做租户隔离】
     *
     * @param sysRoleDTO
     * @param pageNo
     * @param pageSize
     * @return
     */
    //@RequiresPermissions("system:role:list")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public MatApiResponse<Page<SysRoleDTO>> queryPageList(@SpringQueryMap SysRoleDTO sysRoleDTO,
                                                           @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                           @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest req = attributes.getRequest();

        MatApiResponse<Page<SysRoleDTO>> matApiResponse = new MatApiResponse<>();
        SysRole role = toSysRole(sysRoleDTO);

        QueryWrapper<SysRole> queryWrapper = QueryGenerator.initQueryWrapper(role, req.getParameterMap());
        Page<SysRole> page = new Page<SysRole>(pageNo, pageSize);
        IPage<SysRole> pageList = sysRoleService.page(page, queryWrapper);
        matApiResponse.setSuccess(true);
        matApiResponse.setData(toSysRoleDTOPage(pageList));
        return matApiResponse;
    }

    /**
     * 分页列表查询【租户角色，做租户隔离】
     *
     * @param sysRoleDTO
     * @param pageNo
     * @param pageSize
     * @return
     */
    @RequestMapping(value = "/listByTenant", method = RequestMethod.GET)
    public MatApiResponse<Page<SysRoleDTO>> listByTenant(@SpringQueryMap SysRoleDTO sysRoleDTO,
                                                          @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                          @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest req = attributes.getRequest();

        MatApiResponse<Page<SysRoleDTO>> matApiResponse = new MatApiResponse<>();
        SysRole role = toSysRole(sysRoleDTO);

        //------------------------------------------------------------------------------------------------
        //是否开启系统管理模块的多租户数据隔离【SAAS多租户模式】
        if (MybatisPlusSaasConfig.OPEN_SYSTEM_TENANT_CONTROL) {
            role.setTenantId(oConvertUtils.getInt(TenantContext.getTenant(), 0));
        }
        //------------------------------------------------------------------------------------------------
        QueryWrapper<SysRole> queryWrapper = QueryGenerator.initQueryWrapper(role, req.getParameterMap());
        Page<SysRole> page = new Page<SysRole>(pageNo, pageSize);
        IPage<SysRole> pageList = sysRoleService.page(page, queryWrapper);
        matApiResponse.setSuccess(true);
        matApiResponse.setData(toSysRoleDTOPage(pageList));
        return matApiResponse;
    }

    /**
     * 添加
     *
     * @param sysRoleDTO
     * @return
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    //@RequiresPermissions("system:role:add")
    public MatApiResponse<SysRoleDTO> add(@RequestBody SysRoleDTO sysRoleDTO) {
        MatApiResponse<SysRoleDTO> matApiResponse = new MatApiResponse<>();
        SysRole role = toSysRole(sysRoleDTO);

        try {
            role.setCreateTime(new Date());
            sysRoleService.save(role);
            matApiResponse.success("添加成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            matApiResponse.fail("操作失败");
        }
        return matApiResponse;
    }

    /**
     * 编辑
     *
     * @param sysRoleDTO
     * @return
     */
    //@RequiresPermissions("system:role:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public MatApiResponse<SysRoleDTO> edit(@RequestBody SysRoleDTO sysRoleDTO) {
        MatApiResponse<SysRoleDTO> matApiResponse = new MatApiResponse<>();
        SysRole role = toSysRole(sysRoleDTO);

        SysRole sysrole = sysRoleService.getById(role.getId());
        if (sysrole == null) {
            matApiResponse.fail("未找到对应实体");
        } else {
            role.setUpdateTime(new Date());
            boolean ok = sysRoleService.updateById(role);
            //TODO 返回false说明什么？
            if (ok) {
                matApiResponse.success("修改成功!");
            }
        }

        return matApiResponse;
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    //@RequiresPermissions("system:role:delete")
    @RequestMapping(value = "/delete", method = RequestMethod.DELETE)
    public MatApiResponse<?> delete(@RequestParam(name = "id", required = true) String id) {
        sysRoleService.deleteRole(id);
        return MatApiResponse.success("删除角色成功");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    //@RequiresPermissions("system:role:deleteBatch")
    @RequestMapping(value = "/deleteBatch", method = RequestMethod.DELETE)
    public MatApiResponse<SysRoleDTO> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        MatApiResponse<SysRoleDTO> matApiResponse = new MatApiResponse<>();

        if (oConvertUtils.isEmpty(ids)) {
            matApiResponse.fail("未选中角色！");
        } else {
            sysRoleService.deleteBatchRole(ids.split(","));
            matApiResponse.success("删除角色成功!");
        }
        return matApiResponse;
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/queryById", method = RequestMethod.GET)
    public MatApiResponse<SysRoleDTO> queryById(@RequestParam(name = "id", required = true) String id) {
        MatApiResponse<SysRoleDTO> matApiResponse = new MatApiResponse<>();
        SysRole sysrole = sysRoleService.getById(id);
        if (sysrole == null) {
            matApiResponse.fail("未找到对应实体");
        } else {
            matApiResponse.setData(toSysRoleDTO(sysrole));
            matApiResponse.setSuccess(true);
        }
        return matApiResponse;
    }

    /**
     * 查询全部角色（参与租户隔离）
     *
     * @return
     */
    @RequestMapping(value = "/queryall", method = RequestMethod.GET)
    public MatApiResponse<List<SysRoleDTO>> queryall() {
        MatApiResponse<List<SysRoleDTO>> matApiResponse = new MatApiResponse<>();
        LambdaQueryWrapper<SysRole> query = new LambdaQueryWrapper<SysRole>();
        //------------------------------------------------------------------------------------------------
        //是否开启系统管理模块的多租户数据隔离【SAAS多租户模式】
        if (MybatisPlusSaasConfig.OPEN_SYSTEM_TENANT_CONTROL) {
            query.eq(SysRole::getTenantId, oConvertUtils.getInt(TenantContext.getTenant(), 0));
        }
        //------------------------------------------------------------------------------------------------
        List<SysRole> list = sysRoleService.list(query);
        if (list == null || list.size() <= 0) {
            matApiResponse.fail("未找到角色信息");
        } else {
            matApiResponse.setData(toSysRoleDTOList(list));
            matApiResponse.setSuccess(true);
        }
        return matApiResponse;
    }

    /**
     * 查询全部系统角色（不做租户隔离）
     *
     * @return
     */
    //@RequiresPermissions("system:role:queryallNoByTenant")
    @RequestMapping(value = "/queryallNoByTenant", method = RequestMethod.GET)
    public MatApiResponse<List<SysRoleDTO>> queryallNoByTenant() {
        MatApiResponse<List<SysRoleDTO>> matApiResponse = new MatApiResponse<>();
        LambdaQueryWrapper<SysRole> query = new LambdaQueryWrapper<SysRole>();
        List<SysRole> list = sysRoleService.list(query);
        if (list == null || list.size() <= 0) {
            matApiResponse.fail("未找到角色信息");
        } else {
            matApiResponse.setData(toSysRoleDTOList(list));
            matApiResponse.setSuccess(true);
        }
        return matApiResponse;
    }

    /**
     * 校验角色编码唯一
     */
    @RequestMapping(value = "/checkRoleCode", method = RequestMethod.GET)
    public MatApiResponse<Boolean> checkUsername(String id, String roleCode) {
        MatApiResponse<Boolean> matApiResponse = new MatApiResponse<>();
        //如果此参数为false则程序发生异常
        matApiResponse.setData(true);
        log.info("--验证角色编码是否唯一---id:" + id + "--roleCode:" + roleCode);
        try {
            SysRole role = null;
            if (oConvertUtils.isNotEmpty(id)) {
                role = sysRoleService.getById(id);
            }
            SysRole newRole = sysRoleService.getOne(new QueryWrapper<SysRole>().lambda().eq(SysRole::getRoleCode, roleCode));
            if (newRole != null) {
                //如果根据传入的roleCode查询到信息了，那么就需要做校验了。
                if (role == null) {
                    //role为空=>新增模式=>只要roleCode存在则返回false
                    matApiResponse.setSuccess(false);
                    matApiResponse.setMessage("角色编码已存在");
                    return matApiResponse;
                } else if (!id.equals(newRole.getId())) {
                    //否则=>编辑模式=>判断两者ID是否一致-
                    matApiResponse.setSuccess(false);
                    matApiResponse.setMessage("角色编码已存在");
                    return matApiResponse;
                }
            }
        } catch (Exception e) {
            matApiResponse.setSuccess(false);
            matApiResponse.setData(false);
            matApiResponse.setMessage(e.getMessage());
            return matApiResponse;
        }
        matApiResponse.setSuccess(true);
        return matApiResponse;
    }

    /**
     * 导出excel
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(SysRoleDTO sysRoleDTO) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        SysRole sysRole = toSysRole(sysRoleDTO);

        //------------------------------------------------------------------------------------------------
        //是否开启系统管理模块的多租户数据隔离【SAAS多租户模式】
        if (MybatisPlusSaasConfig.OPEN_SYSTEM_TENANT_CONTROL) {
            sysRole.setTenantId(oConvertUtils.getInt(TenantContext.getTenant(), 0));
        }
        //------------------------------------------------------------------------------------------------

        // Step.1 组装查询条件
        QueryWrapper<SysRole> queryWrapper = QueryGenerator.initQueryWrapper(sysRole, request.getParameterMap());
        //Step.2 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        List<SysRole> pageList = sysRoleService.list(queryWrapper);
        //导出文件名称
        mv.addObject(NormalExcelConstants.FILE_NAME, "角色列表");
        mv.addObject(NormalExcelConstants.CLASS, SysRole.class);
        LoginUserDTO user = sessionService.getLoginUser();
        ;
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("角色列表数据", "导出人:" + user.getRealname(), "导出信息"));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public MatApiResponse<?> importExcel() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            // 获取上传文件对象
            MultipartFile file = entity.getValue();
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                return sysRoleService.importExcelCheckRoleCode(file, params);
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return MatApiResponse.fail("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    log.error(e.getMessage(), e);
                }
            }
        }
        return MatApiResponse.fail("文件导入失败！");
    }

    /**
     * 查询数据规则数据
     */
    @GetMapping(value = "/datarule/{permissionId}/{roleId}")
    public MatApiResponse<?> loadDatarule(@PathVariable("permissionId") String permissionId, @PathVariable("roleId") String roleId) {
        List<SysPermissionDataRule> list = sysPermissionDataRuleService.getPermRuleListByPermId(permissionId);
        if (list == null || list.size() == 0) {
            return MatApiResponse.fail("未找到权限配置信息");
        } else {
            Map<String, Object> map = new HashMap(5);
            map.put("datarule", list);
            LambdaQueryWrapper<SysRolePermission> query = new LambdaQueryWrapper<SysRolePermission>()
                    .eq(SysRolePermission::getPermissionId, permissionId)
                    .isNotNull(SysRolePermission::getDataRuleIds)
                    .eq(SysRolePermission::getRoleId, roleId);
            SysRolePermission sysRolePermission = sysRolePermissionService.getOne(query);
            if (sysRolePermission == null) {
                //return Result.error("未找到角色菜单配置信息");
            } else {
                String drChecked = sysRolePermission.getDataRuleIds();
                if (oConvertUtils.isNotEmpty(drChecked)) {
                    map.put("drChecked", drChecked.endsWith(",") ? drChecked.substring(0, drChecked.length() - 1) : drChecked);
                }
            }
            return MatApiResponse.success(map);
            //TODO 以后按钮权限的查询也走这个请求 无非在map中多加两个key
        }
    }

    /**
     * 保存数据规则至角色菜单关联表
     */
    @PostMapping(value = "/datarule")
    public MatApiResponse<?> saveDatarule(@RequestBody JSONObject jsonObject) {
        try {
            String permissionId = jsonObject.getString("permissionId");
            String roleId = jsonObject.getString("roleId");
            String dataRuleIds = jsonObject.getString("dataRuleIds");
            log.info("保存数据规则>>" + "菜单ID:" + permissionId + "角色ID:" + roleId + "数据权限ID:" + dataRuleIds);
            LambdaQueryWrapper<SysRolePermission> query = new LambdaQueryWrapper<SysRolePermission>()
                    .eq(SysRolePermission::getPermissionId, permissionId)
                    .eq(SysRolePermission::getRoleId, roleId);
            SysRolePermission sysRolePermission = sysRolePermissionService.getOne(query);
            if (sysRolePermission == null) {
                return MatApiResponse.fail("请先保存角色菜单权限!");
            } else {
                sysRolePermission.setDataRuleIds(dataRuleIds);
                this.sysRolePermissionService.updateById(sysRolePermission);
            }
        } catch (Exception e) {
            log.error("SysRoleController.saveDatarule()发生异常：" + e.getMessage(), e);
            return MatApiResponse.fail("保存失败");
        }
        return MatApiResponse.success("保存成功!");
    }


    /**
     * 用户角色授权功能，查询菜单权限树
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/queryTreeList", method = RequestMethod.GET)
    public MatApiResponse<Map<String, Object>> queryTreeList(HttpServletRequest request) {
        MatApiResponse<Map<String, Object>> matApiResponse = new MatApiResponse<>();
        //全部权限ids
        List<String> ids = new ArrayList<>();
        try {
            LambdaQueryWrapper<SysPermission> query = new LambdaQueryWrapper<SysPermission>();
            query.eq(SysPermission::getDelFlag, CommonConstant.DEL_FLAG_0);
            query.orderByAsc(SysPermission::getSortNo);
            List<SysPermission> list = sysPermissionService.list(query);
            for (SysPermission sysPer : list) {
                ids.add(sysPer.getId());
            }
            List<TreeModel> treeList = new ArrayList<>();
            getTreeModelList(treeList, list, null);
            Map<String, Object> resMap = new HashMap(5);
            //全部树节点数据
            resMap.put("treeList", treeList);
            //全部树ids
            resMap.put("ids", ids);
            matApiResponse.setData(resMap);
            matApiResponse.setSuccess(true);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return matApiResponse;
    }

    private void getTreeModelList(List<TreeModel> treeList, List<SysPermission> metaList, TreeModel temp) {
        for (SysPermission permission : metaList) {
            String tempPid = permission.getParentId();
            TreeModel tree = new TreeModel(permission.getId(), tempPid, permission.getName(), permission.getRuleFlag(), permission.isLeaf());
            if (temp == null && oConvertUtils.isEmpty(tempPid)) {
                treeList.add(tree);
                if (!tree.getIsLeaf()) {
                    getTreeModelList(treeList, metaList, tree);
                }
            } else if (temp != null && tempPid != null && tempPid.equals(temp.getKey())) {
                temp.getChildren().add(tree);
                if (!tree.getIsLeaf()) {
                    getTreeModelList(treeList, metaList, tree);
                }
            }

        }
    }


    private Page<SysRoleDTO> toSysRoleDTOPage(IPage<SysRole> pageList) {
        Page<SysRoleDTO> sysRoleDTOPage = new Page<>();
        List<SysRoleDTO> sysRoleDTOList = new ArrayList<>();
        if (pageList != null && CollectionUtils.isNotEmpty(pageList.getRecords())) {
            for (SysRole sysRole : pageList.getRecords()) {
                sysRoleDTOList.add(toSysRoleDTO(sysRole));
            }
        }

        sysRoleDTOPage.setTotal(pageList.getTotal());
        sysRoleDTOPage.setSize(pageList.getSize());
        sysRoleDTOPage.setCurrent(pageList.getCurrent());
        sysRoleDTOPage.setRecords(sysRoleDTOList);
        return sysRoleDTOPage;
    }

    private SysRoleDTO toSysRoleDTO(SysRole sysRole) {
        if (sysRole == null) {
            return null;
        }
        SysRoleDTO sysRoleDTO = new SysRoleDTO();
        sysRoleDTO.setId(sysRole.getId());
        sysRoleDTO.setRoleName(sysRole.getRoleName());
        sysRoleDTO.setRoleCode(sysRole.getRoleCode());
        sysRoleDTO.setDescription(sysRole.getDescription());
        sysRoleDTO.setCreateBy(sysRole.getCreateBy());
        sysRoleDTO.setCreateTime(sysRole.getCreateTime());
        sysRoleDTO.setUpdateBy(sysRole.getUpdateBy());
        sysRoleDTO.setUpdateTime(sysRole.getUpdateTime());
        sysRoleDTO.setTenantId(sysRole.getTenantId());
        return sysRoleDTO;
    }

    private SysRole toSysRole(SysRoleDTO sysRoleDTO) {
        if (sysRoleDTO == null) {
            return null;
        }
        SysRole sysRole = new SysRole();
        sysRole.setId(sysRoleDTO.getId());
        sysRole.setRoleName(sysRoleDTO.getRoleName());
        sysRole.setRoleCode(sysRoleDTO.getRoleCode());
        sysRole.setDescription(sysRoleDTO.getDescription());
        sysRole.setCreateBy(sysRoleDTO.getCreateBy());
        sysRole.setCreateTime(sysRoleDTO.getCreateTime());
        sysRole.setUpdateBy(sysRoleDTO.getUpdateBy());
        sysRole.setUpdateTime(sysRoleDTO.getUpdateTime());
        sysRole.setTenantId(sysRoleDTO.getTenantId());
        return sysRole;
    }

    private List<SysRoleDTO> toSysRoleDTOList(List<SysRole> list) {
        List<SysRoleDTO> sysRoleDTOList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(list)) {
            for (SysRole sysRole : list) {
                sysRoleDTOList.add(toSysRoleDTO(sysRole));
            }
        }

        return sysRoleDTOList;
    }

}
